"""
    Author:
    Date: 2018-12-18

    直播管理类
"""
import requests

from django.conf import settings
from requests.auth import HTTPBasicAuth
from utils.log import Log


def get_cast_channel_list():
    """ 获取直播频道列表

        返回的数据结构为:

         {
              "success": true,
              "data": {
                  "channels": [
                      {
                          "channel_name": "lkj144",
                          "user_count": 3
                      }
                  ],
                  "total_size": 3
              }

         }
    """

    base_url = settings.AGORA_BASE_URL
    app_id = settings.AGORA_APP_ID
    url = f'{base_url}/channel/{app_id}'
    params = {
        'page_no': 0,
        'page_size': 100,
    }

    custom_id = settings.AGORA_CUSTOMER_ID
    custom_certificate = settings.AGORA_CUSTOMER_CERTIFICATE
    rsp = requests.get(url, params=params, auth=(custom_id, custom_certificate))
    content, err = _parse_get_response(rsp)
    if err:
        Log.error(f'Get cast channel failed: {err}')
        return None

    return content['data']


def _parse_get_response(rsp):
    """ 解析请求返回的json数据，返回相对应的dict, 错误信息 """
    if 200 != rsp.status_code:
        return None, {'code': rsp.status_code, 'msg': 'http error'}

    try:
        content = rsp.json()
    except Exception as e:
        return None, {'code': 9999, 'msg': e}

    if 'success' in content and not content['success']:
        # return None, {'code': content['errcode'], 'msg': content['errmsg']}
        return None, {'code': 9998, 'msg': 'request failed'}

    return content, None


if __name__ == '__main__':
    print('ok')
